package com.smf.lsc.core.exception;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常配置文件装载
 * @author ln
 *
 */
@Slf4j
public class ExceptionPropertiesUtil {
	private static Properties props;

	synchronized public static void loadProps() {
		props = new Properties();
		InputStream in = null;
		try {
			in = ExceptionPropertiesUtil.class.getResourceAsStream("/exception.properties");
			if (in != null) {
				props.load(new InputStreamReader(in, "UTF-8"));
			}
		} catch (FileNotFoundException e) {
			log.error("装载exception.properties文件未找到", e);
		} catch (IOException e) {
			log.error("装载exception.properties出现IOException", e);
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				log.error("exception.properties文件流关闭出现异常", e);
			}
		}
		log.info("[SMF-LSC] Exception transcoding configuration loaded");
	}

	public static String getProperties(String key) {
		return getProperties(key, (String) null);
	}

	public static String getProperties(String key, String defaultValue) {
		if (props == null) {
			return defaultValue;
		}
		return props.getProperty(key, defaultValue);
	}

	public static String getProperties(String key, Map<String, String> map) {
		return getProperties(key, map, null);
	}

	public static String getProperties(String key, Map<String, String> map, String defaultValue) {
		if (props == null) {
			return defaultValue;
		}
		String message = props.getProperty(key, defaultValue);
		for (String mapKey : map.keySet()) {
			try {
				message = message.replace("{" + mapKey + "}", map.get(mapKey));
			} catch (Exception ignored) {
			}
		}
		return message;
	}

}